package com.example.service;

import com.example.entity.SearchHistory;
import com.example.mapper.RelatedTermsRepository;

import com.example.mapper.SearchHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.entity.RelatedTerms;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class SearchService {

    private final RelatedTermsRepository relatedTermsRepository;
    private final SearchHistoryRepository searchHistoryRepository;

    public SearchService(RelatedTermsRepository relatedTermsRepository,
                         SearchHistoryRepository searchHistoryRepository) {
        this.relatedTermsRepository = relatedTermsRepository;
        this.searchHistoryRepository = searchHistoryRepository;
    }

    public List<String> getRelatedSearchTerms(List<String> keywords) {
        List<String> suggestions = new ArrayList<>();
        for (String keyword : keywords) {
            suggestions.addAll(relatedTermsRepository.findBySearchTermContaining(keyword)
                    .stream()
                    .map(RelatedTerms::getRelatedTerm)
                    .collect(Collectors.toList()));
        }
        return suggestions;
    }


    public void saveSearchHistory(Long userId, String searchTerm) {
        SearchHistory searchHistory = new SearchHistory();
        searchHistory.setUserId(userId);
        searchHistory.setSearchTerm(searchTerm);
        searchHistory.setSearchTime(new Date());

        searchHistoryRepository.save(searchHistory);
    }

}
